package com.eascs.banknet.boc.service.trans;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.jdom.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.banknet.boc.base.BOCUtil;
import com.eascs.banknet.boc.dao.BOC002Dao;
import com.eascs.banknet.boc.service.BOCAbstractService;
import com.eascs.banknet.boc.vo.boc002.BOC002Element;
import com.eascs.banknet.boc.vo.boc002.BOC002Root;
import com.eascs.banknet.common.utils.XmlHelp;
import com.eascs.banknet.constant.EAContant;
import com.eascs.banknet.log.entity.LogEntity;
import com.eascs.common.util.StringUtil;

@Service("boc002Service")
public class BOC002Service extends BOCAbstractService {
	private static final Logger logger = LoggerFactory.getLogger(BOC002Service.class);

	@Autowired
	private BOC002Dao boc002Dao;

	@Autowired
	private BOCUtil bocUtil;

	private String startId;

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, String> dowork() {
		Map<String, String> result = new HashMap<>();
		String id = System.currentTimeMillis() + "";
		
		/**
		 * 查询数据，组装请求xml（批量处理，每次最多100条）
		 */
		try {
			logger.info("BOC002Service-查询贷款状态***********");
			logger.info("查询贷款状态调用开始......");
			// 获取业务数据，
			List<BOC002Element> dataList = boc002Dao.queryData(startId);
			if (dataList.isEmpty()) {
				startId = null;
				logger.info("查询贷款状态,没有符合条件的数据");
				return null;
			}
			if (dataList.size() >= 30) {
				startId = dataList.get(dataList.size() - 1).getAPPNO();
			}else{
				startId = null;
			}

			// 请求组装xml消息
			BOC002Root root = new BOC002Root();
			root.getBody().setList(dataList);
			String xml = XmlHelp.convertToXml(root);
			// 保存xml到ftp服务器
			XmlHelp.createXml("002" + "(" + id + ")", id + "&" + xml, "BOC002RQ", bocUtil.getEaFtpInfo());

			/*
			 * 调用中行接口
			 */
			logger.info("组装请求数据完成，开始调用中行002接口");
			String returnXml = bocNetService.executeSocket(bocUtil.getBocSocketInfo(), "002", null, xml);
			if (StringUtil.isEmpty(returnXml)) {
				logger.error("中行002接口返回数据为空！");
				throw new Exception("中行002接口返回数据为空");
			}
			logger.info("中行002接口返回xml完成,returnXml:[{}]", returnXml);

			// 保存中行返回的xml信息
			XmlHelp.createXml("002" + "(" + id + ")", returnXml, "BOC002RS", bocUtil.getEaFtpInfo());
			// 解析服务器返回的XML
			Element rsRoot = XmlHelp.getRootByString(returnXml);
			Element head = rsRoot.getChild("HEADER");
			String trncod_rs = head.getChildText("RETCODE") == null ? "" : head.getChildText("RETCODE");
			if (!EAContant.BOC001RS.equals(trncod_rs.toLowerCase())) {
				throw new Exception(rsRoot.getChildText("NOTE"));
			}
			Document doc = DocumentHelper.parseText(returnXml);
			org.dom4j.Element node = doc.getRootElement();
			org.dom4j.Element body = node.element("BODY");
			org.dom4j.Element output = body.element("OUTPUT");
			// 获取xml主数据贷款流水状态
			List<org.dom4j.Element> outputList = output.elements("TASKLOG");
			if (!outputList.isEmpty()) {
				for (org.dom4j.Element element : outputList) {
					LogEntity logEntity = initLogData();
					String appno = element.elementText("APPNO");// 申请编号
					String status = element.elementText("STATUS");// 申请编号
					logger.info("查询贷款状态,返回信息,appno:[{}], status:[{}]", appno, status);
					// 写日志到数据库
					logService.writeLog(logEntity, appno, LogEntity.RESULT_TYPE_SUCCESS, status);
					int rw = boc002Dao.updateInfo(status, appno);
					if (rw <= 0) {
						logger.error("更新贷款状态失败,appno:[{}], status:[{}]", appno, status);
						logService.writeLog(logEntity, appno, LogEntity.RESULT_TYPE_SUCCESS, null);
					}
				}
			}
		} catch (Exception e) {
			logger.error("查询贷款状态出现异常，errMsg：[{}]", e);
			// logService.writeLog(logEntity, id, LogEntity.RESULT_TYPE_ERROR,
			// e.getMessage());
		}
		return result;
	}

	@Override
	public LogEntity initLogData() {
		LogEntity logEntity = new LogEntity();
		logEntity.setBankType(LogEntity.BANK_TYPE_BOC);
		logEntity.setTransType("002");
		logEntity.setTypeName("查询贷款状态");
		logEntity.setStartTime(new Date());
		return logEntity;
	}
}
